package com.ywyself.dao;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import com.jfinal.kit.LogKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;
import com.ywyself.ext.kit.YsKit;
import com.ywyself.model.Option;

public class OptionDao {
	private static final String TABLE_NAME = "ys_option";

	/**
	 * 获取网站的配置信息
	 * 
	 * @return data中的数据对象是List<SiteConfig>
	 */
	public YsKit getAll() {
		try {
			StringBuilder sb = new StringBuilder("SELECT * FROM " + TABLE_NAME);
			List<Option> list = Option.dao.find(sb.toString());
			return YsKit.ok().msg("获取网站配置成功").data(list);
		} catch (Exception e) {
			LogKit.error("OptionDao.getAll():" + e.getLocalizedMessage());
			return YsKit.sqlError();
		}
	}

	/**
	 * 更新网站配置
	 * 
	 * @param map
	 *            更新的数据
	 * @return
	 */
	public YsKit update(Map<String, String> map) {
		try {
			boolean isSuccess = Db.tx(new IAtom() {
				@Override
				public boolean run() throws SQLException {
					boolean isOk = true;
					for (Entry<String, String> entry : map.entrySet()) {
						StringBuilder sb = new StringBuilder();
						sb.append("UPDATE " + TABLE_NAME + " SET cfg_value = '")
								.append(entry.getValue().replace("'", "\\'").replace("\"", "\\\""))
								.append("' WHERE cfg_key = '").append(entry.getKey()).append("'");
						isOk = Db.update(sb.toString()) > 0;
						if (!isOk) {
							break;
						}
					}
					return isOk;
				}
			});
			if (isSuccess) {
				return YsKit.ok().code("101").msg("更新成功");
			} else {
				return YsKit.fail().code("400").msg("更新失败");
			}
		} catch (Exception e) {
			LogKit.error("SiteConfigDao.update():" + e.getLocalizedMessage());
			return YsKit.sqlError().code("410");
		}
	}
}
